package com.dengpp.pdform.provider;

import android.content.Context;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;

import androidx.core.content.FileProvider;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class FileProviderHelper {
    private static final String TAG = "FileProviderHelper";

    public static Uri getUriForFile(Context context, String fileName) {
        File photoFile = createImageFile(context, fileName);
        if (photoFile != null) {
            try {
                return FileProvider.getUriForFile(context,
                        getFileProviderAuthority(context),
                        photoFile);
            } catch (IllegalArgumentException e) {
                Log.e(TAG, "FileProvider authority error", e);
                return null;
            } catch (Exception e) {
                Log.e(TAG, "Error getting URI for file", e);
                return null;
            }
        }
        return null;
    }

    private static File createImageFile(Context context, String fileName) {
        File imageFile = null;
        try {
            // 优先使用外部存储的公共图片目录
            File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);

            // 如果外部存储不可用，使用应用专属目录
            if (storageDir == null || !storageDir.exists()) {
                storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
                if (storageDir == null) {
                    storageDir = new File(context.getFilesDir(), "Pictures");
                }
            }

            // 确保目录存在
            if (!storageDir.exists()) {
                if (!storageDir.mkdirs()) {
                    Log.e(TAG, "Failed to create directory: " + storageDir.getAbsolutePath());
                    // 尝试使用缓存目录作为最后的手段
                    storageDir = context.getCacheDir();
                }
            }

            if (storageDir != null && storageDir.exists()) {
                imageFile = new File(storageDir, fileName);

                // 如果文件已存在，删除它
                if (imageFile.exists()) {
                    if (!imageFile.delete()) {
                        Log.w(TAG, "Could not delete existing file: " + imageFile.getAbsolutePath());
                    }
                }

                // 创建新文件
                if (imageFile.createNewFile()) {
                    Log.d(TAG, "Created file: " + imageFile.getAbsolutePath());
                } else {
                    Log.e(TAG, "Failed to create file: " + imageFile.getAbsolutePath());
                    imageFile = null;
                }
            }
        } catch (IOException e) {
            Log.e(TAG, "Error creating image file", e);
        } catch (SecurityException e) {
            Log.e(TAG, "Security exception creating image file", e);
        }
        return imageFile;
    }

    /**
     * 获取FileProvider的authority
     */
    private static String getFileProviderAuthority(Context context) {
        // 首先尝试使用库的包名
        String libraryAuthority = "com.example.attributeform.library.fileprovider";
        try {
            // 检查库的FileProvider是否存在
            context.getPackageManager().getProviderInfo(
                    new android.content.ComponentName("com.example.attributeform.library",
                            "androidx.core.content.FileProvider"), 0);
            return libraryAuthority;
        } catch (Exception e) {
            // 如果库的FileProvider不存在，使用应用的包名
            return context.getPackageName() + ".fileprovider";
        }
    }

    public static String generateImageFileName() {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        return "IMG_" + timeStamp + ".jpg";
    }

    public static String generateVideoFileName() {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        return "VID_" + timeStamp + ".mp4";
    }

    /**
     * 检查外部存储是否可用
     */
    public static boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        return Environment.MEDIA_MOUNTED.equals(state);
    }

    /**
     * 检查外部存储是否至少可读
     */
    public static boolean isExternalStorageReadable() {
        String state = Environment.getExternalStorageState();
        return Environment.MEDIA_MOUNTED.equals(state) ||
                Environment.MEDIA_MOUNTED_READ_ONLY.equals(state);
    }
}
